from flask import Blueprint, render_template, request, redirect, url_for, session
from exts import db
from models import studentModel, UserModel, Exam, Question

# 这里定义的权限视图函数url前缀为"/backend"
bp = Blueprint("backend", __name__, url_prefix="/backend")


# 这里直接将学生信息的后台管理页面作为后台首页了
@bp.route("/", methods=['GET', 'POST'])
def backEndIndex():
    user = UserModel.query.filter_by(userType="student")
    return render_template("backEndStu.html", items=user)


@bp.route("/addStu", methods=['GET', 'POST'])
def addStu():
    if request.method == 'GET':
        return render_template("backEndAddStu.html")
    else:
        # todo:这里从管理员后台提交的数据只做了用户名的检测，直接存储到数据库，这里可以改进一下
        userName = request.form.get("userName")
        if not userName:
            print("用户名为空，请重新输入！")
            return render_template("backEndAddStu.html", errorType=100)
        passWord = request.form.get("passWord")
        name = request.form.get("name")
        schoolId = request.form.get("schoolId")
        school = request.form.get("school")
        major = request.form.get("major")
        userType = "student"
        user = UserModel.query.filter_by(
            userName=userName, userType=userType).first()
        if user:
            print("该用户名已被注册，请重新新输入！")
            return render_template("backEndAddStu.html", errorType=200)
        student = studentModel(userName=userName, passWord=passWord, trueName=name,
                               school=school, schoolId=schoolId, major=major, userType=userType)
        db.session.add(student)
        db.session.commit()
        return redirect(url_for("backend.backEndIndex"))


@bp.route("/modStu", methods=['GET', 'POST'])
def modStu():
    if request.method == 'GET':
        return render_template("backEndModStu.html")
    else:
        # todo:同样是对于待修改的数据，没有做格式检查，只做了用户名的检测，直接将修改后的结果存入数据库中(如果该用户在数据库中)
        userName = request.form.get("userName")
        user = UserModel.query.filter_by(
            userName=userName, userType="student").first()
        if not user:
            print("该用户名不存在，请重新输入")
            return render_template("backEndModStu.html", errorType=101)
        # 这里先暂时假设不能修改用户名
        passWord = request.form.get("passWord")
        trueName = request.form.get("trueName")
        schoolId = request.form.get("schoolId")
        school = request.form.get("school")
        major = request.form.get("major")
        user.passWord = passWord
        user.school = school
        user.trueName = trueName
        user.schoolId = schoolId
        user.major = major
        db.session.commit()
        return redirect(url_for("backend.backEndIndex"))


@bp.route("/delStu", methods=['POST'])
def delStu():
    # 将前端提交的数据在数据库中做查询，如果有则删除，没有打印报错信息
    userName = request.form.get("userName")
    user = UserModel.query.filter_by(
        userName=userName, userType="student").first()
    if not user:
        print("该用户名不存在，请重新输入")
        return render_template("backEndStu.html", errorType=101)
    db.session.delete(user)
    db.session.commit()
    return redirect(url_for("backend.backEndIndex"))


''' ImmutableMultiDict([('name', 'q'), ('signTime', 'w'), ('doExamTime', 'e'), 
('problem1type', 'singleSelect'), ('problem1content', 'r'), ('problem1choiceA', '1'),
 ('problem1choiceB', '1'), ('problem1choiceC', '1'), ('problem1choiceD', '1'), ('problem1ans', '1')])'''
'''('problem1type', 'text'), ('problem1content', '1'), ('problem1ans', '2'), 
('problem2type', 'multiSelect'), ('problem2content', '1'), ('problem2choiceA', '1'), ('problem2choiceB', '1'), ('problem2choiceC', '1'), ('problem2choiceD', '1'), ('problem2ans', '1')])'''


@bp.route("/showExam", methods=['GET', 'POST'])
def showExam():
    exams = Exam.query.all()
    for exam in exams:
        print(exam.name, exam.sign_time, exam.do_time)
    return render_template("backEndExam.html", exams=exams)


@bp.route("/addExam", methods=['GET', 'POST'])
def addExam():
    # todo: WTF validator
    if request.method == 'POST':
        print(request.form)
        exam_name = request.form.get("name")
        sign_time = request.form.get("signTime")
        do_time = request.form.get("doExamTime")
        exam = Exam(name=exam_name, sign_time=sign_time, do_time=do_time)
        db.session.add(exam)
        problem_id = 1
        while True:
            if request.form.get("problem" + str(problem_id) + "type") is None:
                break
            else:
                problem_type = request.form.get(
                    "problem" + str(problem_id) + "type")
                problem_content = request.form.get(
                    "problem" + str(problem_id) + "content")
                if problem_type == "singleSelect" or problem_type == "multiSelect":
                    for i in range(4):
                        choice = request.form.get(
                            "problem" + str(problem_id) + "choice" + chr(ord('A') + i))
                        if choice is None:
                            break
                        else:
                            problem_content += "|" + choice
                question_type = 2 if problem_type == "text" else 0 if problem_type == "singleSelect" else 1
                correct_ans = request.form.get("problem" + str(problem_id) + "ans")
                question = Question(
                    ctx=problem_content, question_type=question_type, correct_ans=correct_ans)
                exam.questions.append(question)
                db.session.add(question)
                problem_id += 1
        db.session.commit()
        return redirect(url_for("backend.showExam"))
    else:
        return render_template("backEndAddExam.html")
